package com.sailor.schedule;

import com.sailor.config.XxlJobConfig;
import com.sailor.mapper.PersonMapper;
import com.sailor.pojo.Person;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.PostConstruct;


@Component
public class HelloTask {
    private static final Logger log = LoggerFactory.getLogger(XxlJobConfig.class);

    @Autowired
    private PersonMapper personMapper;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private PlatformTransactionManager transactionManager;

//    @PostConstruct
//    public void test() throws Exception {
//        demoJobHandler("");
//    }

    @XxlJob("helloJobHandler")
    public ReturnT<String> demoJobHandler(String param) throws Exception {
        log.info("XXL-JOB, Hello World.");
        // 邮件报警测试
//        int i = 1 / 0;
        addPerson2();
        return ReturnT.SUCCESS;
    }

    @Transactional
    public void addPerson() {
        Person person = new Person();
        person.setName("test");
        // 在这里定义需要进行事务管理的代码块，并在该代码块上添加 @Transactional 注解
        TransactionTemplate transactionTemplate = new TransactionTemplate();
        transactionTemplate.setTransactionManager(transactionManager);
        transactionTemplate.execute(status -> {
            personMapper.addPerson(person);
            int i = 1 / 0;
            // return 什么都可以 如"插入成功"
            return null;
        });

    }

    TransactionCallbackWithoutResult insertUserCallback = new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            Person person = new Person();
            person.setName("test");
            personMapper.addPerson(person);
            int i = 1 / 0;
        }
    };

    @Transactional
    public void addPerson2() {
        try {
            transactionTemplate.execute(insertUserCallback);
        } catch (Exception e) {
            // 手动回滚事务   参数null表示请求一个新事务。如果传递非空参数，则表示请求具有给定名称的已有事务。
            //              由于我们只需要请求当前正在进行的事务，因此传递null表示新事务的请求将被忽略，当前事务将作为结果返回。
            transactionTemplate.getTransactionManager().rollback(transactionTemplate.getTransactionManager().getTransaction(null));
            throw e;
        }

    }


}
